package com.xiaoxiong.mami.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxiong.mami.dao.daomain.UserInfo;
import com.xiaoxiong.mami.dao.daomain.UserToken;
import com.xiaoxiong.mami.http.AppJsonResult;
import com.xiaoxiong.mami.service.TokenService;
import com.xiaoxiong.mami.service.UserAddressService;
import com.xiaoxiong.mami.service.UserInfoService;
import com.xiaoxiong.mami.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * Created by Administrator on 2017/7/27.
 */
@RestController
@RequestMapping("/user")
@Api("用户中心")
public class UserInfoWeb {

    final static Logger logger = Logger.getLogger(UserInfoWeb.class);
    public static final String CHANNLE_XIAO_CHENG_XU = "XiaoChengXu";

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    TokenService tokenService;

    @Autowired
    UserAddressService userAddressService;


    @ApiOperation(value = "获取用户信息", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public JSONObject getUserInfo(@RequestParam String userId) {
        UserInfo userInfo = userInfoService.selectByUserId(userId);
        if (userInfo != null) {
            JSONObject data = new JSONObject();
            logger.info("===获取用户成功===: " + data);
            data.put("userInfo", JSON.toJSONString(userInfo));
            return AppJsonResult.createSuccessResultStr(data);
        }
        logger.error("===获取用户失败===: " + userId);
        return AppJsonResult.createErrorResultStr("用户不存在");
    }

    @ApiOperation(value = "注册用户", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "user", required = true, dataType = "UserInfo", paramType = "query")
    })
    @PostMapping("/register")
    public JSONObject register(@RequestParam String telephone, @RequestParam String password) {
        UserInfo user = userInfoService.selectByTelephone(telephone);
        logger.info("password:" + password);
        if (user != null) {
            return AppJsonResult.createErrorResultStr("用户已存在");
        }
        UserInfo userInfo = new UserInfo();
        String userId = UUIDUtils.createUserId();
        userInfo.setUserId(userId);
        userInfo.setTelephone(telephone);

        UserToken userToken = new UserToken();
        userToken.setUserId(userInfo.getUserId());
        userToken.setToken(UUIDUtils.makeToken());
        tokenService.insertUserToken(userToken);
        int result = userInfoService.insertSelective(userInfo);

        if (result == 1) {
            logger.info("===添加用户成功===: " + telephone);
            return AppJsonResult.createSuccessResultStr(null);
        }
        logger.error("===添加用户失败===: " + telephone);
        return AppJsonResult.createErrorResultStr("注册失败");
    }

    @ApiOperation(value = "手机号码登录", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "telephone", value = "telephone", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "password", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/loginByPhoneAndPassword")
    public JSONObject loginByPhoneAndPassword(@RequestParam String telephone, @RequestParam String password) {
        logger.info("===loginByPhoneAndPassword===telephone" + telephone + "===password" + password);
        logger.info("password:" + password);
        UserInfo userInfo = userInfoService.selectByTelephoneAndPassword(telephone,password);
        if (userInfo != null) {
            UserToken userToken = new UserToken();
            userToken.setUserId(userInfo.getUserId());
            userToken.setToken(UUIDUtils.makeToken());
            int ret = tokenService.insertUserToken(userToken);
            if (ret == 1) {
                JSONObject data = new JSONObject();
                data.put("userId", userInfo.getUserId());
                data.put("token", userToken.getToken());
                return AppJsonResult.createSuccessResultStr(data);
            }
        }
        return AppJsonResult.createTokenInvalidResult("登录失败");
    }

    @ApiOperation(value = "退出账号", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/logout")
    public JSONObject logout(@RequestParam String userId) {
        logger.info("===loginByPhoneAndPassword===userId" + userId);
        int count = tokenService.deleteToken(userId);
        if (count > 0) {
            return AppJsonResult.createSuccessResultMsg("");
        }
        return AppJsonResult.createErrorResultStr("");
    }


    @ApiOperation(value = "更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "user", required = true, dataType = "UserInfo", paramType = "query")
    })
    @PostMapping("updateUser")
    public JSONObject updateUserInfo(@RequestBody UserInfo user) {
        if (user != null && user.getUserId() != null) {
            int result = userInfoService.updateByUserId(user);
            if (result == 1) {
                logger.info("===更新用户信息成功===: " + user);
                return AppJsonResult.createSuccessResultWithMsg(null, "更新用户信息成功");
            }
            logger.error("===更新用户信息失败数据库报错===");
            return AppJsonResult.createErrorResultStr("更新用户信息失败");
        }
        logger.error("===更新用户信息失败===: " + user);
        return AppJsonResult.createErrorResultStr("用户参数有误");
    }





}
